package com.seleniti.enpareja.web.desktop.server.model.integration.service.impl.appengine;

import java.util.List;

import org.apache.log4j.Logger;
import org.ioc.commons.utils.Format;
import org.ioc.commons.utils.jdo.JdoQueryHelper;

import com.seleniti.enpareja.controller.common.domain.Page;
import com.seleniti.enpareja.controller.common.exception.EnParejaException;
import com.seleniti.enpareja.controller.model.integration.database.domain.Couple;
import com.seleniti.enpareja.controller.model.integration.database.domain.HomeTask;
import com.seleniti.enpareja.controller.model.integration.database.domain.Product;
import com.seleniti.enpareja.controller.model.integration.database.domain.Store;

public class GAEPendingShoppingService extends GAEService {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(GAEPendingShoppingService.class);

	public GAEPendingShoppingService() {
		logger.info("GAE Couple service instance");
	}

	public void changeStore(Product element, Store store) {
		String text = element.getText();
		logger.info(Format.substitute("Changing store '{0}' to '{1}' from element '{2}'", element.getWhere().getName(),
				store.getName(), text));
		boolean pending = element.isPending();

		element.getWhere().getProducts().remove(element);
		
		Product newElement = new Product();
		newElement.setPending(pending);
		newElement.setWhere(store);
		newElement.setText(text);
		
		if(!store.getCouple().getPendingAtStore().contains(store)) {
			store.getCouple().getPendingAtStore().add(store);
		}
		
		store.getProducts().add(newElement);

		pm.makePersistent(store);
		pm.makePersistent(newElement);
	}

	public void delete(HomeTask ht) throws EnParejaException {
		pm.deletePersistent(ht);
	}

	public Page<HomeTask> getPage(long start, long length) {

		Page<HomeTask> page = new Page<HomeTask>();

		JdoQueryHelper qh = JdoQueryHelper.newQuery(pm, HomeTask.class);

		addLoggedUserCoupleFilter(qh);

		qh.setResult("count(this)");
		Long total = (Long) qh.execute();

		qh.setRange(start, start + length);
		qh.setResult("this");

		List<HomeTask> users = (List<HomeTask>) qh.execute();

		page.setTotal(total != null ? total.longValue() : 0l);
		page.setElements(users);

		return page;

	}

	public HomeTask createTask(String coupleId) {
		logger.info("Creating task for couple " + coupleId);
		HomeTask ht = new HomeTask();

		Couple couple = pm.getObjectById(Couple.class, coupleId);

		ht.setCouple(couple);

		couple.getHomeTasks().add(ht);

		// pm.makePersistent(ht);

		return ht;
	}
}
